import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { localKey } from '@/const';
import dayjs from 'dayjs';
import { loadData, type LoadData } from '../../lib/index';

export function useData() {
  /**
   * 保存文件到本地
   * @param data
   * @returns
   */
  function saveData(data: string | ArrayBuffer | null | undefined) {
    // TODO优先级5 加人验证json-schema
    return new Promise((resovle, reject) => {
      if (!data) {
        reject('无法读取数据');
      }
      try {
        sessionStorage.removeItem(localKey);

        const json = JSON.parse(data as string);
        const apiCollection = json.apiCollection;
        const schemaCollection = json.schemaCollection;
        const dateTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        const result = {
          apiCollection,
          schemaCollection,
          dateTime,
        };
        sessionStorage.setItem(localKey, JSON.stringify(result));
        resovle(result);
      } catch (error) {
        reject('保存出错');
      }
    });
  }

  const apiFoxText = ref('');
  const apiFoxCode = ref('');
  const dateTimeRef = ref('');
  const apiFoxJSON = ref<LoadData | null>(null);

  function readLocal() {
    const apiFoxTextLocal = sessionStorage.getItem(localKey);

    if (apiFoxTextLocal) {
      apiFoxText.value = apiFoxTextLocal;
      try {
        apiFoxJSON.value = JSON.parse(apiFoxText.value);
        apiFoxCode.value = JSON.stringify(apiFoxJSON, null, 2);
        dateTimeRef.value = JSON.parse(apiFoxText.value).dateTime;
      } catch (err) {
        message.error('无法解析');
      }
    }
  }

  function clearLocal() {
    sessionStorage.removeItem(localKey);
    apiFoxCode.value = '';
    dateTimeRef.value = '';
  }

  return {
    apiFoxCode,
    apiFoxJSON,
    dateTimeRef,
    saveData,
    readLocal,
    clearLocal,
  };
}
